/**
 * Description:
 * Class Name:DownLoadUtil
 * Date:2022/5/20 19:12
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第17章_网络编程._17_2_Java的基本网络支持._17_2_3_URL_URLConnection和URLPermission;

import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class DownLoadUtil {
    // 定义下载资源的路径
    private String path;
    // 指定所下载的文件的保存位置
    private String targetFile;
    // 定义需要使用多少个线程下载资源
    private int threadNum;
    // 定义下载的线程对象
    private DownThread[] threads;
    // 定义下载的文件的总大小
    private int fileSize;

    public DownLoadUtil(String path, String targetFile, int threadNum){
        this.path = path;
        this.threadNum = threadNum;
        // 初始化threads 数组
        threads = new DownThread[threadNum];
        this.targetFile = targetFile;
    }

    public void download() throws Exception{
        // 通过域名创建URL对象
        var url = new URL(path);
        // 有了URl对象就可以进行远程对象连接
        var conn = (HttpURLConnection)url.openConnection();
        conn.setConnectTimeout(5 * 1000);
        // 请求方法
        conn.setRequestMethod("GET");
        conn.setRequestProperty(
                "Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
                        + "application/x-shockwave-flash, application/xaml+xml, "
                        + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
                        + "application/x-ms-application, application/vnd.ms-excel, "
                        + "application/vnd.ms-powerpoint, application/msword, */*"
        );
        conn.setRequestProperty("Accept-Language", "zh-CN");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Connection", "Keep-Alive");
        // 得到文件大小
        fileSize = conn.getContentLength();
        conn.disconnect();
        // 根据目标文件大小来划分每个线程所需要下载的大小，+1是为了防止目标过小导致结果为0
        int currentPartSize = fileSize / threadNum + 1;
        var file = new RandomAccessFile(targetFile, "rw");
        // 在本地磁盘上创建一个与网络资源具有相同大小的空文件
        file.setLength(fileSize);
        file.close();
        for (int i = 0; i < threadNum; i++) {
            // 计算每个线程下载的开始位置
            var startPos = i * currentPartSize;
            // 每个线程使用一个RandomAccessFile 进行下载
            var currentPart = new RandomAccessFile(targetFile, "rw");
            // 在目标文件中定位到该线程的下载位置
            currentPart.seek(startPos);
            // 依次创建、启动下载线程来下载网络资源的指定部分
            threads[i] = new DownThread(startPos, currentPartSize, currentPart);
            threads[i].start();
        }
    }

    // 获取下载的完成百分比
    public double getCompleteRate(){
        // 统计多个线程已经下载的总大小
        var sumSize = 0;
        for (int i = 0; i < threadNum; i++) {
            sumSize += threads[i].length;
        }
        // 返回已经完成的百分比
        return sumSize * 1.0 / fileSize;
    }

    private class DownThread extends Thread{
        // 当前线程的下载位置
        private int startPos;
        // 定义当前线程负责下载的文件大小
        private int currentPartSize;
        // 当前线程需要下载的文件块
        private RandomAccessFile currentPart;
        // 定义该线程已下载的字节数
        public int length;
        public DownThread(int startPos, int currentPartSize, RandomAccessFile currentPart){
            this.startPos = startPos;
            this.currentPartSize = currentPartSize;
            this.currentPart = currentPart;
        }

        @Override
        public void run() {
            try {
                var url = new URL(path);
                var conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5 * 1000);
                // 请求方法
                conn.setRequestMethod("GET");
                conn.setRequestProperty(
                        "Accept",
                        "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
                                + "application/x-shockwave-flash, application/xaml+xml, "
                                + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
                                + "application/x-ms-application, application/vnd.ms-excel, "
                                + "application/vnd.ms-powerpoint, application/msword, */*"
                );
                conn.setRequestProperty("Accept-Language", "zh-CN");
                conn.setRequestProperty("Charset", "UTF-8");
                InputStream inputStream = conn.getInputStream();
                // 跳过startPos个字节，表明该线程只下载自己负责的那部分文件
                inputStream.skip(this.startPos);
                // 网络数据都是字节类型的，所以用一个字节类型的数组容器去接
                var buffer = new byte[1024];
                var hasRead = 0;
                // 读取网络数据，并写入本地文件
                while (length < currentPartSize && (hasRead = inputStream.read(buffer)) != -1){
                    // 当没有读完数据并且可以读到数据时，继续循环
                    currentPart.write(buffer, 0, hasRead);
                    // 累计该线程下载的总大小
                    length += hasRead;
                }
                // 关闭写入的文件
                currentPart.close();
                // 关闭对URL资源的读取
                inputStream.close();
            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}
